package com.enjoyor.soa.traffic.ping.efoms.dubbo;

import com.enjoyor.soa.traffic.api.dto.efoms.PingResultDto;
import com.enjoyor.soa.traffic.ping.efoms.pojo.PingResultPojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassNameSendResultService
 * @Description TODO
 * @Author ZSY
 * @Date 2019/2/19 9:54
 * @Version 1.0
 **/
@Component
public class ResultSendService {

    @Value("${ping.send.size}")
    private int sendSize;

    public static final List sendList = new CopyOnWriteArrayList<PingResultPojo>();

    public static final BlockingQueue<PingResultDto> resultQueue = new LinkedBlockingQueue<>();

    private static AtomicInteger checkNull = new AtomicInteger(0);

    private static volatile ResultSendService instance;

    /**
     * 启动一条线程，保持向主程序进行发包操作
     * @return
     */
    @Scheduled(fixedDelay = 5000)
    public ResultSendService getInstance() {
        if (instance == null) {
            synchronized (ResultSendService.class) {
                if (instance == null) {
                    instance = new ResultSendService();
                    Thread thread = new Thread(new SengResultDataThread());
                    thread.setName("T-->ServerPush");
                    thread.start();
                }
            }
        }
        return instance;
    }

    /**
     * 执行线程
     */
    class SengResultDataThread implements Runnable {
        @Override
        public void run() {
            getInstance().sendResultByCount();
        }

    }

    /**
     *
     * 从队列中获取结果
     * 每100个结果进行一次结果的发送
     * 每连续5个null结果将当前结果进行发送
     * @throws InterruptedException
     */
    public void sendResultByCount(){
        while (true){
            PingResultDto pingResultDto = resultQueue.poll();
            List sendList = new ArrayList<PingResultPojo>();
            if (pingResultDto != null) {
                sendList.add(pingResultDto);
                if (sendList.size() >= sendSize) {
                    //TODO 发送100个数据
                    System.out.println(sendList+"============================");
                    System.out.println("数组长度：" + sendList.size());
                    checkNull.set(0);
                    break;
                }
            } else {
                if(sendList!=null&&sendList.size()>0){
                    if (checkNull.addAndGet(1)>5){
                        //TODO 发送数据
                        System.out.println(sendList+"============================");
                        System.out.println("数组长度：" + sendList.size());
                    }
                }
            }
        }

    }
}

